//
//  ST_ConversationAdapter.swift
//  btvideo
//
//  Created by mac on 2020/6/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import NIMSDK
import SwiftyJSON
//import DifferenceKit
import RxCocoa
import RxSwift

class ST_ConversationAdapter: NSObject {


//    MARK: - init
    static let shared = ST_ConversationAdapter()
    
    fileprivate var first_pull_task = true
    
    /// IM 登录的 RxSwift  dispose Bag ,内部应用了 retry  , 用于控制 cancel
    var cancellable_dispose_bag: DisposeBag?
    
    private override init() {
        super.init()
        
        ST_NIMSessionListInfoProvider.shared.clearTask()
        
        NIMSDK.shared().conversationManager.add(self)
        
        NIMSDK.shared().loginManager.add(self)
        
        refresh_session_signal.debounce(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).subscribe(onNext: {
            
            self.refresh_signal_handle()
            
        }).disposed(by: rx.disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().subscribe(onNext: { loginState in
            
            if loginState {
                
                self.start_login_i_m_service()
                
            }else{
                
                self.logout_i_m_service()
            }
            
        }).disposed(by: rx.disposeBag)
        
        
    }
    
    /*
    fileprivate func reloadChanges(newSource:[ST_TianSessionSummaryStruct]){
        
        let changes = StagedChangeset.init(source: sessionList, target: newSource)
        
//        位置没有改变，但是可能有未读消息数更新
        if changes.count == 0{
            
            self.sessionList = newSource
            
//            self.delegate?.update_displaying_cells_data()
            
            self.delegates.forEach({ ($0.value as? ST_ConversationAdapterUIUpdateDelegate)?.update_displaying_cells_data() })
            
            return
        }
        
        if let d = delegate{
            
            d.reload(using: changes, setData: { (list) in
                self.sessionList = list
            })
            
        }else{
            
            self.sessionList = newSource
        }
        
    }
    */
//    MARK: - Properties
    private let refresh_session_signal = PublishRelay<Void>()
    
    /// 消息列表
    private(set) var sessionList = [ST_TianSessionSummaryStruct]()
    
    /// 数据源监听
    let recent_session_observer = BehaviorSubject<[ST_TianSessionSummaryStruct]>(value: [])
    
    
    let added_element_observer = PublishSubject<ST_TianSessionSummaryStruct>()
    
    /// 未读消息
    let unread_number_observer = BehaviorSubject<Int>(value: 0)
}
//MARK: NIMConversationManagerDelegate
extension ST_ConversationAdapter:NIMConversationManagerDelegate{
    
    func did_load_all_recent_session_completion() {
        
        print("异步会话兑换完成!!")
        main_thread_execute {
            self.refresh_all_data()
        }
        
    }
    
    /*
    fileprivate func deleteDuplicateConversation(before:[ST_ConversationSummarryModel]){
            
        var array = before
        
//        array.removeDuplicates(keyPath: \.sessionId)
        
//         Top of Chat when the user is male sorted by [guardTop]
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            array = array.sorted { $0.guardTop && !$1.guardTop }
        }
        
        self.data_array = array
        
        self.listDataDelegate?.refresh_all_data()
        
        
    }*/
    
}

//MARK: - about data_array Method
extension ST_ConversationAdapter{
    
    /// 清空最近聊天列表
    func clear_recent_sessions(){
        
        
        NIMSDK.shared().conversationManager.allRecentSessions()?.forEach({ recentSession in
            
            guard let session = recentSession.session,SYSTEM_SESSION_SET.contains(session.sessionId) == false else{
                return
            }
            
            NIMSDK.shared().conversationManager.markAllMessagesRead(in: session)
            
            NIMSDK.shared().conversationManager.delete(recentSession)
            
        })
        
        main_thread_execute(afterDelay: 1.5) {
            self.refresh_all_data()
        }
        
    }
    
    func clear_data(){
        
        
//        reloadChanges(newSource: [])
        sessionList.removeAll()
        
        recent_session_observer.onNext(sessionList)
        
        first_pull_task = true
        
        BINP.clearTask()
    }
    
    func sortBy(guardIds:Set<String>){
        
        sessionList.forEach({
            
            if guardIds.contains($0.sessionId){
                $0.guardTop = true
            }
        })
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            
            sessionList = sessionList.sorted { $0.guardTop && !$1.guardTop }
//            reloadChanges(newSource: newSessions)
            
            recent_session_observer.onNext(sessionList)
            
        }
        
    }
    
    /// 刷新tableView  更新Cell 位置使用
    @objc func refresh_all_data(){
        
        refresh_session_signal.accept(())
        
    }
    
    fileprivate func refresh_signal_handle(){
//        ST_BTLaunchController.shared.setting_unread_msg_count()
        
//        修改为 网易云 为准
        print("【NIM allRecentSessions】",Date())
        
        guard let sessions = NIMSDK.shared().conversationManager.allRecentSessions()else{
            return
        }
        
        var newSessions = sessions.map{ ST_TianSessionSummaryStruct.decode($0) }.compactMap{ $0 }
        
//          order by [guardTop]
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            newSessions = newSessions.sorted { $0.guardTop && !$1.guardTop }
        }
        
        if sessionList.count > 0{
            
            var addedSessions = Set(newSessions.map{ $0.sessionId })
            addedSessions.subtract(Set(sessionList.map{ $0.sessionId }))
            
            
            if let firstSessionId = addedSessions.first,let element = newSessions.first { $0.sessionId == firstSessionId }{
                
                self.added_element_observer.onNext(element)
                
            }
            
        }
       
        
        
        sessionList = newSessions
        
        recent_session_observer.onNext(sessionList)
         
        let number = NIMSDK.shared().conversationManager.allUnreadCount()
        
        unread_number_observer.onNext(number)
        
        
        if newSessions.count > 0{
            
            BINP.createPullTask(sessions: newSessions,isFirst: first_pull_task)
            
            first_pull_task = false
        }
        
        
        print("【NIM allRecentSessions end】",Date(),"--count:",sessions.count)
    }
    
    // 标记已读
    func mark_read(sessionId:String){
        
        let session = NIMSession.init(sessionId, type: NIMSessionType.P2P)
        
        NIMSDK.shared().conversationManager.markAllMessagesRead(in: session)
        
//        ST_BTLaunchController.shared.setting_unread_msg_count()
        
        guard let found = self.sessionList.first(where: { $0.sessionId == sessionId }) else{
            return
        }
        
        found.unReadCount = 0
        
//        self.delegate?.updateCellData(sessionData: found)
        
        recent_session_observer.onNext(sessionList)
        
        let number = NIMSDK.shared().conversationManager.allUnreadCount()
        
        unread_number_observer.onNext(number)
    }
    
    
    
    func modify_my_guard(sentId:String) {
        
        
        var updateSessions = sessionList
        
        updateSessions.first(where: { $0.guardTop })?.guardTop = false
        
        updateSessions.first(where: { $0.sessionId == sentId })?.guardTop = true
        
        
//         Top of Chat when the user is male sorted by [guardTop]
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male{
            updateSessions = updateSessions.sorted { $0.guardTop && !$1.guardTop }
        }
        
        sessionList = updateSessions
        
        
//        reloadChanges(newSource: updateSessions)
        
        recent_session_observer.onNext(sessionList)
    }
    
    
}


//MARK: - recent local Message

extension ST_ConversationAdapter{
    
    
    /**
     删除本地会话，跟关注不挂钩
     */
    func delete_recent_conversation(sessionId:String){
        
        guard  let recent = NIMSDK.shared().conversationManager.recentSession(by: NIMSession.init(sessionId, type: NIMSessionType.P2P)) , let session = recent.session else{
            return
        }
        
        
        NIMSDK.shared().conversationManager.markAllMessagesRead(in:session)
        NIMSDK.shared().conversationManager.delete(recent)
        
        
        self.refresh_all_data()
        
    }
    
    
}


//
//protocol ST_ConversationAdapterUIUpdateDelegate:AnyObject{
//
//
//    /// Cells 位置发生改变
//    func reload(
//        using stagedChangeset: StagedChangeset<[ST_TianSessionSummaryStruct]>,
//        setData: ([ST_TianSessionSummaryStruct]) -> Void)
//
//
//    /// 单个Cell展示样式
//    func updateCellData(sessionData:ST_TianSessionSummaryStruct)
//
//    /// 更新所有展示的Cell样式
//    func update_displaying_cells_data()
//}
